<?php
/**
 * Created by PhpStorm.
 * User: nightelf
 * Date: 2020/4/17
 * Time: 10:16
 */

namespace App\Http\Model;


use Illuminate\Support\Facades\DB;

class ProjectRosterModel extends Model
{
    const TABLE = 'project_roster';

    public function insert(array $data){
        return DB::table(self::TABLE)->insert($data);
    }

    public function update(array $where ,array $data){
        return DB::table(self::TABLE)->where($where)->update($data);
    }

    public function info(array $where){
        $result = DB::table(self::TABLE)->where($where)->first();
        return empty($result)?[]:get_object_vars($result);
    }

    public function roster(array $info, $projectId)
    {
        $roster = $this->info(['employeeId'=>$info['id'],'projectId'=>$projectId]);
        if (empty($roster)){
            $data = [
                'employeeId'=>$info['id'],
                'projectId'=>$projectId,
                'professionId'=>$info['professionId'],
                'groupId'=>$info['groupId'],
                'isAttendance'=>$info['hasAttendance'],
                'entryTime'=>date('Y-m-d H:i:s'),
                'status'=>1
            ];
            $this->insert($data);
        }else{
            $this->update(['employeeId'=>$info['id'],'projectId'=>$projectId],['status'=>1]);
        }
        if ($info['projectId'] != null){
            $this->update(['employeeId'=>$info['id'],'projectId'=>$info['projectId']],['status'=>0]);
        }
    }

    /**
     * @param array $data
     * @return mixed
     * @throws \Exception
     */
    public function attendance(array $data)
    {
        //获取考勤人员的列表
        $lists = $this->attendanceEmployee($data);
        if (count($lists) == 0) {
            return $lists;
        }

        //获取月考勤，不传月份则默认为当前月份
        $startTime = (new \DateTime($data['month']))->format('Y-m-01');
        $endTime = (new \DateTime($data['month']))->format('Y-m-t');
        $attendanceModel = new AttendanceModel();
        foreach ($lists as $key => $l) {
            $dayList = $this->datePeriod($startTime, $endTime, '1 day', 'j','attendance');
            $attendances = $attendanceModel->getLists(['employeeId'=>$l->id, 'startTime'=>$startTime, 'endTime'=>$endTime]);
            //审批用的状态值
            if(empty($attendances)){
                $status = 3;
            }else{
                $status = 2;
            }
            //对于已经调走的工人是否显示在考勤表中做一个删除状态的判断
//            if ($l->projectId != $data['projectId'] || $l->status == 4){
//                $delete = true;
//            }else{
//                $delete = false;
//            }
            foreach ($attendances as $a) {
                $d = (new \DateTime($a->day))->format('j');
                $dayList[$d]['long'] = empty($a->length)?'':$a->length;
                $dayList[$d]['day'] = empty($a->day)?'':$a->day;
                $dayList[$d]['projectName'] = empty($a->projectName)?'':$a->projectName;
                $projectId = empty($a->projectId)?'':$a->projectId;
                $dayList[$d]['projectId'] = $projectId;
                $dayList[$d]['isCurrent'] = $a->isCurrent;
                //审批用的状态值
                $status = $a->status;
                //如果工人的所有考勤中有至少一条考勤是当前项目的考勤，就出现在考勤列表中
//                if ($projectId == $data['projectId']){
//                    $delete = false;
//                }
            }
            //删除符合已经调走的工人并且当月的所有考勤都不在当前项目记录的条件的工人
//            if ($delete){
//                unset($lists[$key]);
//            }else{
                $lists[$key]->attendance = $dayList;
                //审批用的状态值
                $lists[$key]->attendanceStatus = $status;
//            }

        }

        return array_values($lists);
    }

    private function attendanceEmployee($data)
    {
         $findYear = (new YearModel())->findYear(date('Y-m-d H:i:s', time()));
         if (empty($findYear)) {
             $findYear['startTime'] = date('Y-01-01 00:00:00');
             $findYear['endTime'] = date('Y-12-31 23:59:59');
         }

        $result = DB::table(self::TABLE)
            ->leftJoin('employee', 'employee.id', '=', self::TABLE.'.employeeId')
            ->leftJoin('profession as p', 'p.id', '=', 'employee.professionId')
            ->leftJoin('project', 'project.id', '=', 'employee.projectId')
            ->where(function ($query) use ($data,$findYear) {
                $query->where('hasAttendance', 1)->where('isFinish', 0)->where('employee.status',1)->whereBetween('employee.entryTime', [$findYear['startTime'],$findYear['endTime']]);
                if (isset($data['projectId']) && !empty($data['projectId'])) {
                    $query->where('employee.projectId', $data['projectId'])->where(self::TABLE.'.projectId', $data['projectId']);
                }
//                if (isset($data['month']) && !empty($data['month'])) {
//                    $query->whereBetween('day',[$data['month'].'-01',date('Y-m-t',strtotime($data['month']))]);
//                }else{
                    
//                }
                if (isset($data['professionId']) && !empty($data['professionId'])) {
                    $query->where('employee.professionId', $data['professionId']);
                }
                if (isset($data['search']) && !is_null($data['search'])) {
                    $query->where(function ($query1) use ($data) {
                        $query1->where('employee.name', 'like', '%' . $data['search'] . '%')->orWhere('jobNumber', 'like', '%' . $data['search'] . '%');
                    });
                }

            })
            ->orderBy(self::TABLE.'.status', 'asc')
            ->orderBy('p.order', 'desc')
            ->groupBy(self::TABLE.'.employeeId')
            ->select('employee.*', 'p.name as professionName', 'project.name as projectName',self::TABLE.'.status as rosterStatus');


        if (isset($data['length']) && isset($data['page'])) {
            $limit = config('yucheng.limit');
            $start = 0;
            if (!empty($data['length'])) {
                $limit = $data['length'];
            }
            if (!empty($data['page'])) {
                $start = ($data['page'] - 1) * $limit;
            }
            $result = $result->offset($start)->limit($limit);
        }
        $result = $result->get()->toArray();
        return $result;
    }

}